const db = require('../../db')
// MARK GET / attendances/:page/:pageSize	查询考勤数据列表
exports.getList = (req, res) => {
    console.log("GET / attendances	查询考勤数据列表");
    const { page, pageSize, departmentChecks } = req.query;

    // 验证输入数据
    if (!page || !pageSize || page <= 0 || pageSize <= 0) {
        return res.status(400).json({ success: false, code: 10001, message: '页码和每页大小必须为正整数' });
    }

    // 获取当前年月
    const now = new Date();
    const currYear = now.getFullYear();
    const currMonth = now.getMonth() + 1; // 月份从 1 开始
    const dayNumber = new Date(currYear, currMonth, 0).getDate();
    // 构建查询条件
    const offset = (parseInt(page) - 1) * parseInt(pageSize);

    // 处理 departmentChecks
    let departmentArray = [];
    if (departmentChecks) {
        departmentArray = departmentChecks.split(',').map(Number);
    }

    // 查询 department 表
    let departmentQuery = `
        SELECT 
          id,
          name AS departmentName
        FROM department
    `;
    let departmentValues = [];

    if (departmentArray.length > 0) {
        departmentQuery += ` WHERE id IN (${departmentArray.map(() => '?').join(', ')})`;
        departmentValues = departmentArray;
    }

    db.query(departmentQuery, departmentValues, (err, departmentResults) => {
        if (err) {
            return res.status(500).json({ success: false, code: 10002, message: '查询部门信息失败', error: err.message });
        }

        const departmentMap = departmentResults.reduce((acc, department) => {
            acc[department.id] = department.departmentName;
            return acc;
        }, {});

        // 查询 employee 表
        let employeeQuery = `
            SELECT 
              id AS userId,
              username,
              mobile,
              workNumber,
              departmentId
            FROM employee
        `;
        let employeeValues = [];

        if (departmentArray.length > 0) {
            employeeQuery += ` WHERE departmentId IN (${departmentArray.map(() => '?').join(', ')})`;
            employeeValues = [...departmentArray, parseInt(pageSize), offset];
        } else {
            employeeValues = [parseInt(pageSize), offset];
        }

        employeeQuery += ` LIMIT ? OFFSET ?`;

        db.query(employeeQuery, employeeValues, (err, employeeResults) => {
            if (err) {
                return res.status(500).json({ success: false, code: 10002, message: '查询员工信息失败', error: err.message });
            }

            const userIds = employeeResults.map(employee => employee.userId);

            // 查询 total 记录数
            let totalQuery = `
                SELECT COUNT(*) AS total 
                FROM employee
            `;
            let totalValues = [];

            if (departmentArray.length > 0) {
                totalQuery += ` WHERE departmentId IN (${departmentArray.map(() => '?').join(', ')})`;
                totalValues = departmentArray;
            }

            db.query(totalQuery, totalValues, (err, totalResult) => {
                if (err) {
                    return res.status(500).json({ success: false, code: 10002, message: '查询员工总数失败', error: err.message });
                }

                const total = totalResult[0].total;

                // 查询 attendances 表
                const attendanceQuery = `
                    SELECT 
                      userId,
                      adtStatu,
                      year,
                      month,
                      id
                    FROM attendances
                    WHERE userId IN (${userIds.map(() => '?').join(', ')})
                    AND year = ?
                    AND month = ?
                `;
                const attendanceValues = [...userIds, currYear, currMonth];

                db.query(attendanceQuery, attendanceValues, (err, attendanceResults) => {
                    if (err) {
                        return res.status(500).json({ success: false, code: 10002, message: '查询考勤信息失败', error: err.message });
                    }

                    const attendanceMap = attendanceResults.reduce((acc, attendance) => {
                        if (!acc[attendance.userId]) {
                            acc[attendance.userId] = [];
                        }
                        acc[attendance.userId].push(attendance);
                        return acc;
                    }, {});

                    // 处理结果
                    const rows = employeeResults.map(employee => {
                        const attendanceRecord = attendanceMap[employee.userId] || [];
                        const formattedAttendanceRecord = attendanceRecord.map(attendance => {
                            const adtStatuArray = attendance.adtStatu.split('、').map(Number);
                            const records = [];
                            for (let i = 0; i < dayNumber; i++) {
                                records.push({
                                    day: i + 1,
                                    adtStatu: adtStatuArray[i] || 0,
                                    adtOutTime: null, // 假设 adtOutTime 为 null
                                    adtInTime: null, // 假设 adtInTime 为 null
                                    id: attendance.id,
                                    userId: attendance.userId,
                                    departmentId: employee.departmentId
                                });
                            }
                            return records;
                        }).flat();

                        return {
                            departmentId: employee.departmentId,
                            departmentName: departmentMap[employee.departmentId] || '',
                            id: employee.userId,
                            userId: employee.userId,
                            mobile: employee.mobile,
                            username: employee.username,
                            workNumber: employee.workNumber,
                            attendanceRecord: formattedAttendanceRecord
                        };
                    });

                    // 返回数据
                    res.json({
                        success: true,
                        code: 10000,
                        data: {
                            data: {
                                total,
                                currMonth,
                                currYear,
                                dayNumber,
                                rows
                            }
                        },
                        message: '执行成功'
                    });
                });
            });
        });
    });
};
// MARK PUT / attendances / { id }	编辑考勤记录
exports.putById = (req, res) => {
    const { id } = req.params
    const { day, adtStatu } = req.body

    // 验证输入数据
    if (!id || !day || !adtStatu || day <= 0 || day > 31) {
        return res.status(400).json({ success: false, code: 10001, message: '输入数据无效' })
    }

    // 查询 attendances 表
    const selectQuery = `
        SELECT adtStatu
        FROM attendances
        WHERE id = ?
    `
    const selectValues = [id]

    db.query(selectQuery, selectValues, (err, results) => {
        if (err) {
            return res.status(500).json({ success: false, code: 10002, message: '查询考勤信息失败', error: err.message })
        }

        if (results.length === 0) {
            return res.status(404).json({ success: false, code: 10003, message: '考勤记录不存在' })
        }

        const adtStatuString = results[0].adtStatu
        const adtStatuArray = adtStatuString.split('、').map(Number)

        // 修改第 day 个元素的值
        adtStatuArray[day - 1] = adtStatu

        // 转换回字符串
        const updatedAdtStatuString = adtStatuArray.join('、')

        // 更新 attendances 表
        const updateQuery = `
            UPDATE attendances
            SET adtStatu = ?
            WHERE id = ?
        `
        const updateValues = [updatedAdtStatuString, id]

        db.query(updateQuery, updateValues, (err) => {
            if (err) {
                return res.status(500).json({ success: false, code: 10002, message: '更新考勤信息失败', error: err.message })
            }

            res.json({ success: true, code: 10000, message: '更新成功' })
        })
    })
}

// MARK POST / attendances / signIn 打卡
exports.signIn = (req, res) => {
    const userId = req.user.id;

    // 获取当前日期
    const now = new Date();
    const currYear = now.getFullYear();
    const currMonth = now.getMonth() + 1; // 月份从 1 开始
    const day = now.getDate() - 1; // 获取当前日期是本月的第几天（从 0 开始）

    // 查询 attendances 表
    const selectQuery = `
        SELECT adtStatu
        FROM attendances
        WHERE userId = ? AND year = ? AND month = ?
    `;
    const selectValues = [userId, currYear, currMonth];

    db.query(selectQuery, selectValues, (err, results) => {
        if (err) {
            return res.status(500).json({ success: false, code: 10001, message: '查询考勤信息失败', error: err.message });
        }

        if (results.length === 0) {
            return res.status(404).json({ success: false, code: 10002, message: '考勤记录不存在' });
        }

        // 获取 adtStatu 字段并转换为数组
        const adtStatuString = results[0].adtStatu;
        const adtStatuArray = adtStatuString.split('、').map(Number);

        // 修改第 day 个元素的值
        adtStatuArray[day] = 1;

        // 转换回字符串
        const updatedAdtStatuString = adtStatuArray.join('、');

        // 更新 attendances 表
        const updateQuery = `
            UPDATE attendances
            SET adtStatu = ?
            WHERE userId = ? AND year = ? AND month = ?
        `;
        const updateValues = [updatedAdtStatuString, userId, currYear, currMonth];

        db.query(updateQuery, updateValues, (err) => {
            if (err) {
                return res.status(500).json({ success: false, code: 10003, message: '更新考勤信息失败', error: err.message });
            }

            res.json({
                success: true,
                code: 10000,
                message: '打卡成功'
            });
        });
    });
};
// MARK GET / attendances / reports / year	归档历史列表
// MARK GET / attendances / reports	获取月考勤报表
// MARK GET / attendances / newReports	新建考勤报表
// MARK GET / attendances / archives	月度考勤归档


/**
    * 新建数组rows
    * 根据departmentChecks 数组中的数据查询department表中name命名为departmentName
    * 根据 departmentChecks 去employee表查询出departmentId字段值在查询参数组内的数据
    * {username,id(命名为userId),mobile,workNumber,departmentId,departmentName}插入rows
    * 新建数组attendanceRecord
    * 根据userId查询attendances表中userId字段对应上的数据{adtStatu,year,month,id}
    * 此时adtStatu是一个字符串格式如下：'0、0、0、0、0',其中用、分割了31个数字
    * 此时按照month的值算出当月有多少天存在变量day中,然后把adtStatu转换为原字符串分割的前day个数字组成的数组
    * 对每一个adtStatu都用一个数组存起来格式如下: {
                           "day": "20250301", // 具体某一天
                           "adtStatu": 22,// 状态码
                           "id": 10,
                           "userId": 10,
                           "departmentId": 9
                       }
       最后返回格式如下：
    * 
    */
/**
{
"success": true,
"code": 10000,
"data": {
    "data": {
        "total": 31,
        "rows": [
            {
                "departmentId": 9,// 根据userId查employee表departmentId字段值
                "departmentName": "财务核算部",// 根据departmentId查询department表name字段值
                "id": 10,
                "userId": 10,
                "mobile": "13600000002", // userId查询employee表
                "username": "黑马袁永安", // userId查询employee表
                "workNumber": "HEIMA00010", // userId查询employee表
                "attendanceRecord": [
                    {
                        "day": "20250301", // 具体某一天
                        "adtStatu": 22,// 状态码
                        "adtOutTime": null, // 下班考勤时间
                        "adtInTime": null, // 上班考勤时间
                        "id": 10,
                        "userId": 10,
                        "departmentId": 9
                    }
                ]
            }
        ]
    }
},
"message": "执行成功"
}
*/



/**
 * 
 * 
 exports.getList = (req, res) => {
    console.log("GET / attendances	查询考勤数据列表");
    const { page, pageSize, departmentChecks } = req.query;

    // 验证输入数据
    if (!page || !pageSize || page <= 0 || pageSize <= 0) {
        return res.status(400).json({ success: false, code: 10001, message: '页码和每页大小必须为正整数' });
    }

    // 获取当前年月
    const now = new Date();
    const currYear = now.getFullYear();
    const currMonth = now.getMonth() + 1; // 月份从 1 开始
    const dayNumber = new Date(currYear, currMonth, 0).getDate();
    // 构建查询条件
    const offset = (parseInt(page) - 1) * parseInt(pageSize);

    // 处理 departmentChecks
    let departmentArray = [];
    if (departmentChecks) {
        departmentArray = departmentChecks.split(',').map(Number);
    }

    // 查询 department 表
    let departmentQuery = `
        SELECT 
          id,
          name AS departmentName
        FROM department
    `;
    let departmentValues = [];

    if (departmentArray.length > 0) {
        departmentQuery += ` WHERE id IN (${departmentArray.map(() => '?').join(', ')})`;
        departmentValues = departmentArray;
    }

    db.query(departmentQuery, departmentValues, (err, departmentResults) => {
        if (err) {
            return res.status(500).json({ success: false, code: 10002, message: '查询部门信息失败', error: err.message });
        }

        const departmentMap = departmentResults.reduce((acc, department) => {
            acc[department.id] = department.departmentName;
            return acc;
        }, {});

        // 查询 employee 表
        let employeeQuery = `
            SELECT 
              id AS userId,
              username,
              mobile,
              workNumber,
              departmentId
            FROM employee
        `;
        let employeeValues = [];

        if (departmentArray.length > 0) {
            employeeQuery += ` WHERE departmentId IN (${departmentArray.map(() => '?').join(', ')})`;
            employeeValues = [...departmentArray, parseInt(pageSize), offset];
        } else {
            employeeValues = [parseInt(pageSize), offset];
        }

        employeeQuery += ` LIMIT ? OFFSET ?`;

        db.query(employeeQuery, employeeValues, (err, employeeResults) => {
            if (err) {
                return res.status(500).json({ success: false, code: 10002, message: '查询员工信息失败', error: err.message });
            }

            const userIds = employeeResults.map(employee => employee.userId);

            // 查询 total 记录数
            let totalQuery = `
                SELECT COUNT(*) AS total 
                FROM employee
            `;
            let totalValues = [];

            if (departmentArray.length > 0) {
                totalQuery += ` WHERE departmentId IN (${departmentArray.map(() => '?').join(', ')})`;
                totalValues = departmentArray;
            }

            db.query(totalQuery, totalValues, (err, totalResult) => {
                if (err) {
                    return res.status(500).json({ success: false, code: 10002, message: '查询员工总数失败', error: err.message });
                }

                const total = totalResult[0].total;

                // 查询 attendances 表
                const attendanceQuery = `
                    SELECT 
                      userId,
                      adtStatu,
                      year,
                      month,
                      id
                    FROM attendances
                    WHERE userId IN (${userIds.map(() => '?').join(', ')})
                    AND year = ?
                    AND month = ?
                `;
                const attendanceValues = [...userIds, currYear, currMonth];

                db.query(attendanceQuery, attendanceValues, (err, attendanceResults) => {
                    if (err) {
                        return res.status(500).json({ success: false, code: 10002, message: '查询考勤信息失败', error: err.message });
                    }

                    const attendanceMap = attendanceResults.reduce((acc, attendance) => {
                        if (!acc[attendance.userId]) {
                            acc[attendance.userId] = [];
                        }
                        acc[attendance.userId].push(attendance);
                        return acc;
                    }, {});

                    // 处理结果
                    const rows = employeeResults.map(employee => {
                        const attendanceRecord = attendanceMap[employee.userId] || [];
                        const formattedAttendanceRecord = attendanceRecord.map(attendance => {
                            const adtStatuArray = attendance.adtStatu.split('、').map(Number);
                            const records = [];
                            for (let i = 0; i < dayNumber; i++) {
                                records.push({
                                    day: i + 1,
                                    adtStatu: adtStatuArray[i] || 0,
                                    adtOutTime: null, // 假设 adtOutTime 为 null
                                    adtInTime: null, // 假设 adtInTime 为 null
                                    id: attendance.id,
                                    userId: attendance.userId,
                                    departmentId: employee.departmentId
                                });
                            }
                            return records;
                        }).flat();

                        return {
                            departmentId: employee.departmentId,
                            departmentName: departmentMap[employee.departmentId] || '',
                            id: employee.userId,
                            userId: employee.userId,
                            mobile: employee.mobile,
                            username: employee.username,
                            workNumber: employee.workNumber,
                            attendanceRecord: formattedAttendanceRecord
                        };
                    });

                    // 返回数据
                    res.json({
                        success: true,
                        code: 10000,
                        data: {
                            data: {
                                total,
                                currMonth,
                                currYear,
                                dayNumber,
                                rows
                            }
                        },
                        message: '执行成功'
                    });
                });
            });
        });
    });
};
 */